<?php

class Workset_Filter_DateToTimestamp implements Zend_Filter_Interface
{
	protected static $_filter = null;

    protected $_options = array();

	function __construct($options = null)
    {
    	if ($options !== null) {
			$this->setOptions($options);
		}
    }

	function filter($value) {
		$options = $this->getOptions();
		$filtered = false;

		if (!is_array($value)) {
			$value = $this->_localizedToNormalized($value, $options);
			$filtered = true;
		}

		if ($value && is_array($value)) {
			if (!$filtered) {
				if (isset($options['defaults'])) {
					foreach ($options['defaults'] as $key => $part) {
						if (isset($value[$key])) {
							$value[$part] = $value[$key];
							unset($value[$key]);
						}
					}
				}
			}
			if (isset($options['reqs'])) {
				$value = array_merge($options['reqs'], (array)$value);
			}
			$d = !empty($value['day']) ? $value['day'] : date('j');
			$m = !empty($value['month']) ? $value['month'] : date('n');
			$y = !empty($value['year']) ? $value['year'] : date('Y');
			$time = mktime(0, 0, 0, $m, $d, $y);
		} else {
			$time = time();
		}
        
		return $time;
	}

	function setOptions($options) {
		if (is_string($options) || (count($options) == 1 && is_int(key($options)))) {
			$options = array('date_format' => current((array)$options));
		}
		$this->_options = $options;
	}

	function getOptions() {
        return $this->_options;
    }

    protected function _localizedToNormalized($value, $options) {
        if (self::$_filter === null) {
            self::$_filter = new Zend_Filter_LocalizedToNormalized($options);
        }
        return self::$_filter->filter($value);
    }

}


?>